package com.school.teaching.activity;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import com.alibaba.fastjson.JSONObject;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.school.teaching.R;
import com.school.teaching.constant.ConfigConst;
import com.school.teaching.databinding.ActivityLoginBinding;
import com.school.teaching.util.LogUtils;
import com.school.teaching.util.OkHttpUtils;
import com.trello.rxlifecycle.ActivityEvent;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

public class LoginActivity extends BaseActivity {

    private static final String TAG = "LoginActivity";
    private static int SECOND = 20; //倒计时

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityLoginBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        final Button verifyButton = binding.verifyButton;
        final Button loginButton = binding.loginButton;
        EditText usernameEditText = binding.usernameEditText;
        EditText passwordEditText = binding.passwordEditText;

        Observable<CharSequence> usernameObservable = RxTextView.textChanges(usernameEditText);
        Observable<CharSequence> passwordObservable = RxTextView.textChanges(passwordEditText);
        Observable.combineLatest(usernameObservable, passwordObservable, new Func2<CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean call(CharSequence username, CharSequence password) {
                return isPhoneValid(username.toString()) && isPasswordValid(password.toString());
            }
        }).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                RxView.enabled(loginButton).call(aBoolean);
            }
        });

        RxView.clicks(loginButton)
                .throttleFirst(1, TimeUnit.SECONDS)
                .doOnNext(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        RxView.enabled(loginButton).call(false);
                    }
                })
                /*.observeOn(Schedulers.io()) //运行在新线程中.subscribeOn(Schedulers.io()) //运行在新线程中
                .map(new Func1<Void, String>() {
                    @Override
                    public String call(Void aVoid) {
                        JSONObject msgInfo = new JSONObject();
                        msgInfo.put("sence", "1");

                        String resp = null;
                        try {
                            resp = OkHttpUtils.post(ConfigConst.API_URL, msgInfo.toJSONString());
                        } catch (IOException e) {
                            LogUtils.e(TAG, e.getMessage());
                            resp = null;
                        }
                        LogUtils.i(TAG, "resp=" + resp);
                        return resp;
                    }
                })*/
                .map(new Func1<Void, String>() {
                    @Override
                    public String call(Void aVoid) {
                        return "hello";
                    }
                })
                /*.flatMap(new Func1<Void, Observable<String>>() {
                    @Override
                    public Observable<String> call(Void aVoid) {
                        JSONObject msgInfo = new JSONObject();
                        msgInfo.put("sence", "1");

                        String resp = null;
                        try {
                            resp = OkHttpUtils.post(ConfigConst.API_URL, msgInfo.toJSONString());
                        } catch (IOException e) {
                            LogUtils.e(TAG, e.getMessage());
                            resp = null;
                        }
                        LogUtils.i(TAG, "resp=" + resp);
                        return Observable.just(resp);
                    }
                })*/
                .doOnUnsubscribe(new Action0() {
                    @Override
                    public void call() {
                        LogUtils.i(TAG, "Unsubscribing subscription from onCreate()");
                    }
                })
                .compose(this.<String>bindUntilEvent(ActivityEvent.PAUSE))
                .filter(new Func1<String, Boolean>() { //过滤序列不为空的元素
                    @Override
                    public Boolean call(String s) {
                        return StringUtils.isNotBlank(s);
                    }
                })
                .take(1) //发射序列前几个元素,takeLast(n)发射序列后几个元素
                .distinct() //去程序列重复元素
                .observeOn(AndroidSchedulers.mainThread()) //让subscriber运行在主线程中
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String msg) {
                        LogUtils.i(TAG, "msg=" + msg);
                        RxView.enabled(loginButton).call(true);
                    }
                });

        RxView.clicks(verifyButton)
                .throttleFirst(1, TimeUnit.SECONDS)
                .doOnNext(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        RxView.enabled(verifyButton).call(false);
                    }
                })
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Observable.interval(1, TimeUnit.SECONDS)
                                .take(SECOND)
                                .observeOn(AndroidSchedulers.mainThread()) //让subscriber运行在主线程中
                                .subscribe(new Subscriber<Long>() {
                                    @Override
                                    public void onCompleted() {
                                        RxTextView.text(verifyButton).call("获取验证码");
                                        RxView.enabled(verifyButton).call(true);
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        LogUtils.e(TAG, e.toString());
                                    }

                                    @Override
                                    public void onNext(Long aLong) {
                                        RxTextView.text(verifyButton).call("剩余" + (SECOND - aLong) + "秒");
                                    }
                                });
                    }
                });
    }

    private boolean isPhoneValid(String phone) {
        return phone.length() == 11;
    }

    private boolean isPasswordValid(String password) {
        return password.length() >= 6;
    }
}
